package com.hmdp.controller;


import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import jodd.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 */
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @GetMapping("list")
    public Result queryTypeList() {
//        //1.获取key
//
//        String key = RedisConstants.CACHE_SHOP_KEY;
//
//
//        String shopTypeJson = stringRedisTemplate.opsForValue().get(key);
//
//
//        //判断是否有缓存
//       if(StringUtil.isNotBlank(shopTypeJson)) {
//
//           //有缓存
//           List<ShopType> shopTypes = JSONUtil.toList(shopTypeJson, ShopType.class);
//           return Result.ok(shopTypes);
//       }
//
//       //没缓存
//
//        List<ShopType> typeList = typeService
//                .query().orderByAsc("sort").list();
//
//       //存入redis
//        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(typeList));
//        return Result.ok(typeList);
//    }
        String key = RedisConstants.CACHE_SHOP_KEY;

        Boolean aBoolean = stringRedisTemplate.hasKey(key);

        if(aBoolean){

            List<String> shopTypeJsonList = stringRedisTemplate.opsForList().range(key, 0, -1);

            List<ShopType> shopTypes = shopTypeJsonList.stream()
                    .map(shopTypeJson -> JSONUtil.toBean(shopTypeJson, ShopType.class))
                    .collect(Collectors.toList());

            return Result.ok(shopTypes);
        }

        List<ShopType> typeLists = typeService
                .query().orderByAsc("sort").list();


        typeLists.stream()
                .map(shopType -> JSONUtil.toJsonStr(shopType))
                .forEach(shopTypeJson -> stringRedisTemplate.opsForList().leftPush(key, shopTypeJson));

        return Result.ok(typeLists);
    }
    }
